package org.zfes.snowier.common.monitor.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Optional;
import org.zfes.snowier.common.monitor.utils.ConfigReader;

public class DBUtil {
	private static final  String configFilePath="config/config.properties";
	private static final  String driverConfigKey="jdbcDriver";
	private static final  String jdbcUrlConfigKey="jdbcUrl";
	private static final  String usernameConfigKey="username";
	private static final  String passwordConfigKey="password";
	
	private static String jdbcDriver;
	private static String jdbcUrl;
	private static String username;
	private static String password;
	

	public static Connection openConn () {
		Connection connection=null;
		try {
			Class.forName(getDriver());
			connection = DriverManager.getConnection(getJdbcUrl(),getUsername(),getPassword());
		 } catch (SQLException |ClassNotFoundException e) {
			 System.out.println("获取连接失败");
	          e.printStackTrace();
	        throw new RuntimeException(e);
		 }
		 return connection;
	}
	
	public static void closeResource(ResultSet rs, Statement st, Connection con) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (st != null) {
				st.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	
	private static String getDriver() {
		if(jdbcDriver==null) {
			Optional<String> cfgOp=ConfigReader.getConfig(configFilePath, driverConfigKey);
			if(cfgOp.isPresent()) {
				jdbcDriver=cfgOp.get();
			}else {
				throw new RuntimeException("未正确配置jdbcDriver");
			}
		}
		return jdbcDriver;
	}
	private static String getJdbcUrl() {
		if(jdbcUrl==null) {
			Optional<String> cfgOp=ConfigReader.getConfig(configFilePath, jdbcUrlConfigKey);
			if(cfgOp.isPresent()) {
				jdbcUrl=cfgOp.get();
			}else {
				throw new RuntimeException("未正确配置jdbcUrl");
			}
		}
		return jdbcUrl;
	}
	private static String getUsername() {
		if(username==null) {
			Optional<String> cfgOp=ConfigReader.getConfig(configFilePath, usernameConfigKey);
			if(cfgOp.isPresent()) {
				username=cfgOp.get();
			}else {
				throw new RuntimeException("未正确配置username");
			}
		}
		return username;
	}
	
	private static String getPassword() {
		if(password==null) {
			Optional<String> cfgOp=ConfigReader.getConfig(configFilePath, passwordConfigKey);
			if(cfgOp.isPresent()) {
				password=cfgOp.get();
			}else {
				throw new RuntimeException("未正确配置password");
			}
		}
		return password;
	}
	
}
